<script setup lang="ts">
import type { InvoicApplyRecord } from '@/api/types/finance'
import type { InfoItem } from '@/components/DetailCard.vue'
import { onPullDownRefresh } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { getInvoicApplyRecordById } from '@/api/finance'
import ApprovalActionBar from '@/components/ApprovalActionBar.vue'
import DetailCard from '@/components/DetailCard.vue'
import { getStatusName } from '@/constants/enums'
import { useFlow } from '@/hooks/useFlow'
import { formatDate } from '@/utils/timeUtils'

definePage({
  style: {
    backgroundColor: '#f5f5f5',
    navigationBarTitleText: '发票申请详情',
    enablePullDownRefresh: true,
  },
})

// 页面参数
const idValue = ref('')
const flowIdValue = ref('')

// 状态变量
const invoiceData = ref<InvoicApplyRecord | null>(null)
const error = ref(false)
const loading = ref(false)
const tabValue = ref(0)

// 使用流程hook
const {
  currentProcess,
  getProcessInstance,
  getCurrentUserPendingTaskId,
  loading: flowLoading,
} = useFlow()

// 整体加载状态
const pageLoading = computed(() => loading.value || flowLoading.value)

// 基本信息
const basicInfo = computed<InfoItem[]>(() => {
  if (!invoiceData.value)
    return []

  return [
    {
      label: '申请单号',
      value: invoiceData.value.businessNo || '-',
      key: 'invoiceNo',
    },
    {
      label: '申请时间',
      value: formatDate(invoiceData.value.createTime || 'datetime_short'),
      key: 'createTime',
      type: 'datetime',
    },
    {
      label: '业务机构',
      value: invoiceData.value.businessInstitutionName || '-',
      key: 'businessInstitutionName',
    },
    {
      label: '业务部门',
      value: invoiceData.value.businessDepartmentName || '-',
      key: 'businessDepartmentName',
    },
    {
      label: '业务员',
      value: invoiceData.value.salesmanName || '-',
      key: 'salesmanName',
    },
  ]
})

// 结算信息
const settlementInfo = computed<InfoItem[]>(() => {
  if (!invoiceData.value)
    return []

  return [
    {
      label: '结算主体',
      value: invoiceData.value.settlementEntityName || '-',
      key: 'settlementEntityName',
    },
    {
      label: '统一信用代码',
      value: invoiceData.value.taxNumber || '-',
      key: 'taxNumber',
      forceMultiline: true,
    },
    {
      label: '客商类型',
      value: getStatusName(invoiceData.value.settlementEntityType || '-', 'customerType') || '-',
      key: 'settlementEntityType',
      type: 'status',
    },
    {
      label: '申请开票金额',
      value: invoiceData.value.totalAmount || 0,
      key: 'totalAmount',
      type: 'currency',
    },
    {
      label: '已核销金额',
      value: invoiceData.value.writeOffAmount || 0,
      key: 'writeOffAmount',
      type: 'currency',
    },
    {
      label: '未核销金额',
      value: invoiceData.value.unwriteOffAmount || 0,
      key: 'unwriteOffAmount',
      type: 'currency',
    },
  ]
})

// 创建人信息
const creatorInfo = computed<InfoItem[]>(() => {
  if (!invoiceData.value)
    return []

  return [
    {
      label: '创建人',
      value: invoiceData.value.createName || '-',
      key: 'createName',
    },
    {
      label: '创建时间',
      value: formatDate(invoiceData.value.createTime || 'datetime_short'),
      key: 'createTime',
      type: 'datetime',
    },
    {
      label: '更新人',
      value: invoiceData.value.updateName || '-',
      key: 'updateName',
    },
    {
      label: '更新时间',
      value: formatDate(invoiceData.value.updateTime || 'datetime_short'),
      key: 'updateTime',
      type: 'datetime',
    },
  ]
})

// 运单信息列表
const waybillInfos = computed<InfoItem[][]>(() => {
  if (!invoiceData.value || !invoiceData.value.waybillInfosList)
    return []

  // 根据运单信息生成InfoItem二维数组
  return invoiceData.value.waybillInfosList.map((waybill) => {
    const items: InfoItem[] = [
      {
        label: '运单号',
        value: waybill.wayBillOrderNumber || '-',
        key: 'waybillNo',
      },
      {
        label: '货物名称',
        value: waybill.waybillOrderItemVoList[0]?.goodName || '-',
        key: 'goodsName',
      },
      {
        label: '运输路线',
        value: `${waybill.startAddr || '-'} → ${waybill.endAddr || '-'}`,
        key: 'route',
        forceMultiline: true,
      },
      {
        label: '车辆信息',
        value: waybill.carVo?.licensePlate || waybill.licensePlate || '-',
        key: 'vehicleInfo',
      },
      {
        label: '司机信息',
        value: waybill.driverVo?.name || '-',
        key: 'driverInfo',
      },
      {
        label: '承运价',
        value: waybill.carrierTotalPrice || 0,
        key: 'carrierTotalPrice',
        type: 'currency',
      },
      {
        label: '货物重量',
        value: `${waybill.allWeightMax || 0}吨`,
        key: 'weight',
      },
      {
        label: '返单时间',
        value: formatDate(waybill.returnVoucherTime || 'datetime_short'),
        key: 'returnVoucherTime',
        type: 'datetime',
      },
    ]

    // 添加结算信息（如果有）
    if (waybill.settlementParams && waybill.settlementParams.length > 0) {
      waybill.settlementParams.forEach((settlement, index) => {
        items.push({
          label: `货主出价${index > 0 ? index + 1 : ''}`,
          value: settlement.amount || 0,
          key: `settlementAmount-${index}`,
          type: 'currency',
        })
      })
    }

    return items
  })
})

// 获取流程实例信息
async function fetchProcessInfo() {
  try {
    await getProcessInstance(idValue.value)
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }
    // 流程信息获取成功后，自动获取业务详情
    if (currentProcess.value.businessKey) {
      await fetchInvoiceDetail(currentProcess.value.businessKey)
    }
  }
  catch (error) {
    console.error('获取流程信息失败:', error)
    uni.showToast({
      title: '获取流程信息失败',
      icon: 'none',
    })
  }
}

// 获取发票申请详情
async function fetchInvoiceDetail(id?: string) {
  if (!id)
    return

  loading.value = true
  error.value = false

  try {
    const res = await getInvoicApplyRecordById(id)
    invoiceData.value = res.data || null
  }
  catch (err) {
    console.error('获取发票申请详情失败:', err)
    error.value = true
    uni.showToast({
      title: '获取发票申请详情失败',
      icon: 'none',
    })
  }
  finally {
    loading.value = false
  }
}

// 初始化时获取详情
onLoad((e: any) => {
  idValue.value = e?.id || ''
  flowIdValue.value = e?.flowId || ''

  if (idValue.value) {
    fetchProcessInfo()
  }
  else {
    uni.showToast({
      title: '页面参数错误',
      icon: 'none',
    })
  }
})

// 下拉刷新数据
onPullDownRefresh(async () => {
  // 如果有流程实例ID，通过流程刷新数据
  if (idValue.value) {
    await fetchProcessInfo()
  }
  uni.stopPullDownRefresh()
})
</script>

<template>
  <view class="overflow-hidden bg-gray-100 py-1">
    <!-- 加载状态 -->
    <view v-if="pageLoading" class="min-h-screen flex items-center justify-center">
      <view class="flex flex-col items-center">
        <text class="mt-4 text-gray-500">加载中...</text>
      </view>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="error" class="min-h-screen flex items-center justify-center">
      <view class="flex flex-col items-center p-6">
        <text class="mt-4 text-base text-gray-500">加载失败</text>
        <button
          class="mt-6 rounded-full bg-blue-500 px-6 py-2 text-white"
          @click="fetchProcessInfo"
        >
          重新加载
        </button>
      </view>
    </view>

    <!-- 正常状态 -->
    <view v-else-if="invoiceData" class="relative">
      <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />

      <wd-tabs v-model="tabValue" swipeable animated sticky :offset-top="0">
        <wd-tab title="基本信息" custom-class="bg-[#f9fafb]">
          <!-- 基本信息 -->
          <DetailCard
            title="基本信息"
            :info-list="basicInfo"
            class="mx-4 mt-4"
          />

          <!-- 结算信息 -->
          <DetailCard
            title="结算信息"
            :info-list="settlementInfo"
            class="mx-4 mt-4"
          />

          <!-- 创建人信息 -->
          <DetailCard
            title="创建人信息"
            :info-list="creatorInfo"
            class="mx-4 mb-6 mt-4"
          />
        </wd-tab>
        <wd-tab title="运单信息" custom-class="bg-[#f9fafb]">
          <!-- 运单信息列表 -->
          <view v-if="waybillInfos.length > 0" class="mx-4 mt-4">
            <view class="mb-3 flex items-center">
              <text class="text-lg text-gray-800 font-medium">运单信息</text>
              <text class="ml-2 text-sm text-gray-500">({{ waybillInfos.length }}条记录)</text>
            </view>

            <view v-for="(waybillItems, index) in waybillInfos" :key="`waybill-${index}`" class="mb-4">
              <DetailCard
                :title="`运单 ${index + 1}`"
                :info-list="waybillItems"
                class="mb-4"
              />
            </view>
          </view>
          <view v-else class="flex items-center justify-center py-10">
            <text class="text-gray-500">暂无运单信息</text>
          </view>
        </wd-tab>
      </wd-tabs>
    </view>

    <!-- 空状态 -->
    <view v-else class="min-h-screen flex items-center justify-center">
      <view class="flex flex-col items-center p-6">
        <text class="mt-4 text-base text-gray-500">暂无发票申请数据</text>
      </view>
    </view>

    <!-- 审批操作栏 -->
    <ApprovalActionBar v-if="flowIdValue && currentProcess?.status === 1" :process-id="flowIdValue" />
  </view>
</template>

<style scoped>
/* 页面样式 */
.container {
  background-color: #f5f5f5;
  position: relative;
}

/* 响应式适配 */
/* #ifdef H5 */
.container {
  min-height: 100vh;
}
/* #endif */

/* #ifdef MP-WEIXIN */
.container {
  min-height: 100vh;
}
/* #endif */

/* #ifdef APP-PLUS */
.container {
  min-height: 100vh;
}
/* #endif */
</style>
